<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/6/8
 * Time: 下午4:48
 */

namespace Modules\Attachment\Controllers;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\Admin\Auth\Facades\AdminAuth;
use App\Models\Attachments;
use Modules\Attachment\Facades\Upload;

class UploadController extends Controller
{
    public function index()
    {
        //
    }

    public function upload(Request $request)
    {
        try {
            $file = $request->file('filedata');
            if (!$file) {
                return fail('请选择上传文件');
            }

            $fileSize = ceil($file->getSize() / 1024);
            $fileExt  = $file->getClientOriginalExtension();
            $fullPath = $file->getRealPath();
            $fileType = !is_image($fullPath) ? Attachments::FILE_TYPE_OTHER : Attachments::FILE_TYPE_IMAGE;
            if ($fileExt) {
                $fileExt = '.' . strtolower($fileExt);
            }

            // 限制大小
            if ($fileType == Attachments::FILE_TYPE_OTHER) {
                if ($fileSize > 51200) {
                    return fail('文件超过限制大小50M');
                }
            } else {
                if ($fileSize > 10240) {
                    return fail('文件超过限制大小10M');
                }
            }

            // 获取文件内容的md5字串作为文件名key
            $fileKey = md5(file_get_contents($fullPath)) . $fileExt;
            // 加上日期目录
            $fileKey = ltrim(env('APP_NAME') . '/' . date('Ymd') . "/$fileKey",'/');
            Log::info($fileKey);
            // 如果上传过直接返回
            if ($attachment = Attachments::where('file_key', $fileKey)->first()) {
                // 删除临时文件
                unlink($fullPath);
                return success(['id' => $attachment->id, 'file_url' => $attachment->file_url]);
            }
            Log::info($fullPath);

            $content = file_get_contents($fullPath);

            //file_put_contents(storage_path(md5(file_get_contents($fullPath)) . $fileExt),$content);

            $fileUrl = Upload::uploadContent($fileKey, $content, [
                'ContentType' => $file->getMimeType()
            ]);

            // 保存图片
            // 上传一个文件(两个参数：索引、文件路径)
            //$fileUrl = Upload::upload($fileKey, $fullPath, [
            //    'ContentType' => $file->getMimeType()
            //]);

            // 获取图片原始宽高
            /*$img_width  = null;
            $img_height = null;
            if ($fileType == Attachments::FILE_TYPE_IMAGE) {
                $imgInfo = $file->getMimeType();
                if ($imgInfo != false) {
                    $img_width  = $imgInfo[0];
                    $img_height = $imgInfo[1];
                }
            }*/

            // 删除临时文件
            unlink($fullPath);

            // 保存到数据库
            $operator_id   = null;
            $operator_type = null;
            $site_id       = null;
            if (AdminAuth::check()) {
                $operator_id   = AdminAuth::user()->id;
                $operator_type = Attachments::OPERATOR_TYPE_ADMIN;
            }
            $id = Attachments::insertGetId([
                'operator_id'   => $operator_id,
                'operator_type' => $operator_type,
                'site_id'       => $site_id,
                'file_key'      => $fileKey,
                'file_url'      => $fileUrl,
                'file_size'     => $fileSize,
                'file_type'     => $fileType,
                'operator_ip'   => $request->ip(),
                //'width'         => $img_width,
                //'height'        => $img_height,
                'created_at'    => Carbon::now()->toDateTimeString(),
            ]);

            return success(['id' => $id, 'file_url' => $fileUrl]);
        } catch (\Exception $e) {
            Log::emergency('上传图片报错日志: ', [$e->getMessage()]);
            Log::error('上传图片详细报错日志: ' . $e->getFile() . ":" . $e->getLine(),$e->getTrace());
            return fail(500, '因系统错误上传失败');
        }
    }



    public function uploadFromUrl(Request $request)
    {
        try {

            $operator_id   = null;
            $operator_type = null;
            $site_id       = null;
            if (AdminAuth::check()) {
                $operator_id   = AdminAuth::user()->id;
                $operator_type = Attachments::OPERATOR_TYPE_ADMIN;
            }

            $response = [];
            $images = $request->input('images');
            foreach($images as $img) {
                $content = file_get_contents($img);
                $fileKey = md5($content);
                // 加上日期目录
                $fileKey = env('APP_NAME') . '/' . date('Ymd') . "/$fileKey";
                // 如果上传过直接返回
                $attachment = Attachments::where('file_key', $fileKey)->first();
                if ($attachment) {
                    $response[] = $attachment->file_url;
                    continue;
                }

                // 上传至oss
                $fileType = "image/jpeg";
                if(($headers = get_headers($img, 1))!==false){
                    $fileType = $headers['Content-Type'];
                }

                // 上传一个文件(两个参数：索引、文件路径)
                $fileUrl = Upload::uploadContent($fileKey, $content, [
                    'ContentType' => $fileType
                ]);

                // 写入attachments表
                Attachments::insertGetId([
                    'operator_id'   => $operator_id,
                    'operator_type' => $operator_type,
                    'site_id'       => $site_id,
                    'file_key'      => $fileKey,
                    'file_url'      => $fileUrl,
                    'file_size'     => 0,
                    'file_type'     => Attachments::FILE_TYPE_IMAGE,
                    'operator_ip'   => $request->ip(),
                    'width'         => 0,
                    'height'        => 0,
                    'created_at'    => Carbon::now()->toDateTimeString(),
                ]);

                $response[] = $fileUrl;
            }
            return success($response);

        } catch(\Exception $e) {
            Log::error($e);
            return fail(500, '上传失败');
        }
    }
}